package com.jason.cloud.engine.share.driver.order.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jason.cloud.engine.share.driver.email.service.EmailService;
import com.jason.cloud.engine.share.driver.enterprise.bean.EnterpriseBean;
import com.jason.cloud.engine.share.driver.enterprise.service.EnterpriseService;
import com.jason.cloud.engine.share.driver.enterprise.util.EnterpriseUtil;
import com.jason.cloud.engine.share.driver.order.bean.OrderBean;
import com.jason.cloud.engine.share.driver.order.service.OrderService;
import com.jason.cloud.engine.share.driver.pack.bean.PackBean;
import com.jason.cloud.engine.share.driver.pack.service.PackService;
import com.jason.cloud.engine.share.driver.user.bean.UserBean;
import com.jason.cloud.engine.share.driver.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private UserService userService;

    @Resource
    private PackService packService;

    @Resource
    private EmailService emailService;

    /**
     * 列举
     * @return
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject getOrderByLimit(@RequestParam int page, @RequestParam int limit) {

        //加载所有
        List<OrderBean> orderList = this.orderService.getOrderByLimit((page - 1 ) * limit, limit);
        int count = this.orderService.getOrderCount();

        //返回值
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", count);

        //遍历数据
        JSONArray jsonArrayPack = new JSONArray();
        OrderBean orderBean = null;
        EnterpriseBean enterpriseBean = null;
        UserBean userBean = null;
        PackBean packBean = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Iterator itr = orderList.iterator(); itr.hasNext();) {
            orderBean = (OrderBean)itr.next();
            JSONObject json = new JSONObject();
            json.put("id", orderBean.getId());
            enterpriseBean = this.enterpriseService.queryEnterpriseById(orderBean.getEnterpriseId().trim());
            json.put("enterpriseName", enterpriseBean.getName());
            userBean = this.userService.queryUserById(orderBean.getUserId().trim());
            json.put("applyUserName", userBean.getName());
            json.put("applyUserTel", userBean.getTel());
            packBean = this.packService.queryPackById(orderBean.getOldPackId().trim());
            json.put("oldPackName", packBean.getName());
            packBean = this.packService.queryPackById(orderBean.getNewPackId().trim());
            json.put("newPackName", packBean.getName());
            json.put("status", orderBean.getStatus()==null?"--":orderBean.getStatus());
            json.put("cycle", orderBean.getCycle());
            json.put("cost", orderBean.getCost());
            json.put("remarks", orderBean.getRemarks()==null?"--":orderBean.getRemarks());
            json.put("createDate", simpleDateFormat.format(orderBean.getCreateDate()));
            jsonArrayPack.add(json);
        }
        jsonObject.put("data", jsonArrayPack);
        return jsonObject;
    }

    /**
     * 增加
     * @param json
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject insertOrder(@RequestBody JSONObject json) {
        //取值
        String enterpriseId = json.getString("enterpriseId");
        String userId = json.getString("userId");
        String packId = json.getString("packId");
        int cycle = json.getInteger("cycle");

        //保存
        JSONObject jsonObject = new JSONObject();
        OrderBean orderBean = new OrderBean();

        //加载企业值
        EnterpriseBean enterpriseBean = this.enterpriseService.queryEnterpriseById(enterpriseId.trim());

        orderBean.setEnterpriseId(enterpriseBean.getId());

        //加载用户值
        UserBean userBean = this.userService.queryUserById(userId.trim());
        orderBean.setUserId(userBean.getId().trim());

        orderBean.setOldPackId(enterpriseBean.getPackId().trim());

        orderBean.setNewPackId(packId.trim());
        orderBean.setCycle(cycle);

        //加载新资费
        PackBean packBean = this.packService.queryPackById(packId.trim());
        orderBean.setCost(packBean.getPrice() * cycle);

        orderBean.setStatus("申请");
        orderBean.setCreateDate(new Date());

        this.orderService.insertOrder(orderBean);

        jsonObject.put("status", "200");
        jsonObject.put("msg", "资费变更申请成功、请付费并等待审核");
        return jsonObject;
    }

    /**
     * 生效订单
     * @return
     */
    @RequestMapping(value = "/effected/{orderId}", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject effectedOrderFormEnterprise(@PathVariable String orderId) {
        //获取订单对象
        OrderBean orderBean = this.orderService.queryOrderById(orderId.trim());

        //获取企业对象
        EnterpriseBean enterpriseBean = this.enterpriseService.queryEnterpriseById(orderBean.getEnterpriseId().trim());

        enterpriseBean.setPackId(orderBean.getNewPackId().trim());
        enterpriseBean.setEndDate(EnterpriseUtil.generateBillExpireDateByStartDate(enterpriseBean.getEndDate(), orderBean.getCycle()));

        //更新绑定到企业的资费
        this.enterpriseService.updateEnterprisePackAndEffect(enterpriseBean);

        //更新订单状态
        orderBean.setStatus("生效");
        this.orderService.updateOrderStatusByOrderId(orderBean);

        //获取用户对象
        UserBean userBean = this.userService.queryUserById(orderBean.getUserId().trim());
        this.emailService.sendEmailByServer("[云引擎服务] 你的订单已审批通过", userBean.getEmail().trim(), "", "你的订单已审批通过，订单号为： " + orderBean.getId());

        //返回值
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 200);
        jsonObject.put("msg", "选择的订单已全部生效");

        return jsonObject;
    }
}
